<script lang="ts" defer async setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { initFaceBook, trackEvent } from '@/utils/facebookService'
import { register, getCode, channel,login } from '@/api/login'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useUserInfo } from '@/store/user'
import eyeOpen from '@/static/img/eye-open.png'
import eyeClose from '@/static/img/eye-close.png'
const userInfoStore = useUserInfo()
const route = useRouter()
const router = useRouter()
const { t } = useI18n()
const isVerify = ref(false)
const baseData = reactive({
  showCheckMachine: false,
  showCountDown: false,
  showPassWord: false,
  showcPassWord: false,
  secounds: 60,
  current: 0,
  registerForm: {
    email: '',
    phone: '',
    password: null,
    code: null,
    confirmPassword: null,
    promo_code: '', 
    source: null, 
  },
  showFullscreenLoading: false,
})

const statTypeExt = ref('')
const getPixelId = async () => {
  const res = await channel({
    source: baseData.registerForm.source,
  })
  if (res.code == 0) {
    
    
    uni.setStorageSync('PixelId', res.data.statId)
    statTypeExt.value = res.data.statTypeExt
    uni.setStorageSync('typeExt', res.data.statTypeExt)
    if (statTypeExt.value === '1') initFaceBook(res.data.statId)
	
  }
}



const changType = (e: any) => {
  baseData.current = e
}
const countDown = ref(null)

const sendCode = async () => {
  const res = await getCode({
    email: baseData.current ? baseData.registerForm.phone : baseData.registerForm.email,
  })
  if (res.code == 0) {
    baseData.showCountDown = true
    countDown.value?.start()
    uni.showToast({
      title: t('Verification Code Sent'),
      icon: 'none',
    })
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}
const pupMachine = () => {
  if (baseData.current == 0) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(baseData.registerForm.email)) {
      uni.showToast({
        title: t('Invalid Email Format'),
        icon: 'none',
      })
      return
    }
  } else {
    const phoneRegex = /^\+?[0-9\s-]{7,15}$/
    if (!phoneRegex.test(baseData.registerForm.phone)) {
      uni.showToast({
        title: t('Invalid Phone Format'),
        icon: 'none',
      })
      return
    }
  }
  
  baseData.showCheckMachine = true
  nextTick(() => {
    if (typeof turnstile !== 'undefined') {
      turnstile.ready(() => {
        turnstile.render('#example-container', {
          sitekey: '0x4AAAAAABbT5VqdBlU9hK-V',
          callback: (token: any) => {
            sendCode()
          },
        })
      })
    }
  })
}
const finishCountTime = () => {
  baseData.showCountDown = false
}
const goLogin = () => {
  window.top?.postMessage('/pages/login/index', window.location.origin)
  uni.navigateTo({
    url: '/pages/login/index',
  })
}
	const goLoginTwo = async () => {
		  const params = {
		    email:  baseData.registerForm.phone? baseData.registerForm.phone: baseData.registerForm.email,
		    password: baseData.registerForm.password,
		  }
		  
		  const res = await login(params)
	
		if (res.code == 0) {
			 
			 
			getPixelId();
			useUserInfo().setUserInfos(res.data)
			useUserInfo().setToken(res.data!.token)
			uni.setStorageSync('hasVisited', 'true');
			uni.setStorageSync('url', '/pages/index/indexContent');
			window.top?.postMessage('/pages/index/indexContent', window.location.origin)
			uni.navigateTo({
				url: '/pages/index/indexContent',
			})
		} else {
			uni.showToast({
				title: res.msg,
				icon: "none"
			})
		}
		
		
		uni.setStorageSync("showTips",1)
	}
const bind = async () => {
  let promo_code = uni.getStorageSync('promo_code')
  if (baseData.current == 0) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(baseData.registerForm.email)) {
      uni.showToast({
        title: t('Invalid Email Format'),
        icon: 'none',
      })
      return
    }
  } else {
    const phoneRegex = /^\+?[0-9\s-]{7,15}$/
    if (!phoneRegex.test(baseData.registerForm.phone)) {
      uni.showToast({
        title: t('Invalid Phone Format'),
        icon: 'none',
      })
      return
    }
  }
  if (baseData.registerForm.password != baseData.registerForm.confirmPassword) {
    uni.showToast({
      title: t('Passwords Do Not Match'),
      icon: 'none',
    })
    return
  }
  if (!baseData.registerForm.password) {
    uni.showToast({
      title: t('Password Cannot Be Empty'),
      icon: 'none',
    })
    return
  }

  const res = await register({
    email: baseData.current ? baseData.registerForm.phone : baseData.registerForm.email,
    password: baseData.registerForm.password,
    
    confirmPassword: baseData.registerForm.confirmPassword,
    promo_code: baseData.registerForm.promo_code, 
    source: baseData.registerForm.source, 
  })
  if (res.code == 0) {
	  baseData.showFullscreenLoading = true
    
    
    if (statTypeExt.value === '1') {
      fbq('track', 'CompleteRegistration')
    }
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
    setTimeout(function () {
      goLoginTwo()
    }, 2000)
  } else {
	  baseData.showFullscreenLoading = false
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}
const Verification = async () => {
  nextTick(() => {
    if (typeof turnstile !== 'undefined') {
      turnstile.ready(() => {
        turnstile.render('#example-container', {
          sitekey: '0x4AAAAAAB0lPnsxk6EzCv4K',
          callback: (token: any) => {
            isVerify.value = true
          },
          'error-callback': (error: any) => {
            isVerify.value = false
          },
        })
      })
    }
  })
}
const leftClick = () => {
	window.top?.postMessage('/pages/login/guide', window.location.origin)
		uni.navigateTo({
		  url: '/pages/login/guide',
		})
}
onMounted(() => {
  
  
  uni.setNavigationBarTitle({
    title: 'Studio ' + t('Earn money so easy') + '!', 
  })
  Verification()
  
  const url = new URL(window.location.href)
  const params = new URLSearchParams(url.search)
  console.log(uni.getStorageSync('promo_code'), uni.getStorageSync('code'))

  
  if (route.currentRoute.value.query.code) {
    uni.setStorageSync('code', route.currentRoute.value.query.code)
    baseData.registerForm.source = route.currentRoute.value.query.code
    uni.removeStorageSync('promo_code')
    window.top?.postMessage(`/pages/index/index`, window.location.origin)
    uni.navigateTo({
      url: '/pages/index/index',
    })
  }
  
  if (route.currentRoute.value.query.promo_code) {
    uni.setStorageSync('promo_code', route.currentRoute.value.query.promo_code)
    baseData.registerForm.promo_code = route.currentRoute.value.query.promo_code
    uni.removeStorageSync('code')
    window.top?.postMessage(`/pages/index/index`, window.location.origin)
    uni.navigateTo({
      url: '/pages/index/index',
    })
  }
  if (uni.getStorageSync('promo_code')) {
    baseData.registerForm.promo_code = uni.getStorageSync('promo_code')
    baseData.registerForm.source = null
	 getPixelId()
  }

  if (uni.getStorageSync('code')) {
    baseData.registerForm.source = uni.getStorageSync('code')
     getPixelId()
  }
 
})
</script>

<template>
  <view class="register-container">
    
    <view class="simple-header">
      <view class="back-button" @click="leftClick">
        <image class="back-icon" src="@/static/img/left.png"></image>
      </view>
      <text class="page-title">{{t('Create Account')}}</text>
      <view class="header-spacer"></view>
    </view>

    
    <view class="main-content">
      
      <!-- <view class="brand-section">
        <view class="logo-container">
          <image class="logo" src="@/static/img/logo.png"/>
        </view>
      </view> -->

      
      <view class="form-container">
        
        <view class="tab-switcher">
          <view 
            class="tab-item" 
            :class="{ active: baseData.current === 0 }"
            @click="changType(0)"
          >
            <text class="tab-text">{{ t('Email') }}</text>
          </view>
          <view 
            class="tab-item" 
            :class="{ active: baseData.current === 1 }"
            @click="changType(1)"
          >
            <text class="tab-text">{{t('Phone')}}</text>
          </view>
        </view>

        
        <view class="input-group">
          <view class="input-wrapper" v-show="baseData.current === 0">
            <up-input 
              v-model="baseData.registerForm.email"
              type="email"
              :placeholder="t('Email')"
              class="input-field"
			  prefixIcon="email-fill"
			  prefixIconStyle="font-size: 18px;color: #FE8400"
            />
          </view>

          <view class="input-wrapper" v-show="baseData.current === 1">
            <up-input 
              v-model="baseData.registerForm.phone"
              type="tel"
              :placeholder="t('Phone Number')"
              class="input-field"
			  prefixIcon="phone-fill"
			  prefixIconStyle="font-size: 18px;color: #FE8400"
            />
          </view>

          <view class="input-wrapper">
            <up-input 
              v-model="baseData.registerForm.password"
              :type="baseData.showPassWord ? 'text' : 'password'"
              :placeholder="t('Password')"
              class="input-field"
			   prefixIcon="lock-fill"
			   prefixIconStyle="font-size: 18px;color: #FE8400"
            />
            <view 
              class="password-toggle" 
              @click="baseData.showPassWord = !baseData.showPassWord"
            >
              <image class="toggle-icon" :src="baseData.showPassWord ? eyeOpen : eyeClose"/>
            </view>
          </view>

          <view class="input-wrapper">
            <up-input 
              v-model="baseData.registerForm.confirmPassword"
              :type="baseData.showcPassWord ? 'text' : 'password'"
              :placeholder="t('Confirm password')"
              class="input-field"
			   prefixIcon="lock-fill"
			   prefixIconStyle="font-size: 18px;color: #FE8400"
            />
            <view 
              class="password-toggle" 
              @click="baseData.showcPassWord = !baseData.showcPassWord"
            >
              <image class="toggle-icon" :src="baseData.showcPassWord ? eyeOpen : eyeClose"/>
            </view>
          </view>
        </view>

        
        <view class="invite-code-section" v-if="baseData.registerForm.source || baseData.registerForm.promo_code">
          <view class="invite-badge">
            <text class="badge-text">
              {{ t('Invitation Code') }}: {{ baseData.registerForm.source || baseData.registerForm.promo_code }}
            </text>
          </view>
        </view>

        
        <view class="verification-section">
          <view class="verification-title">{{ t('Security Verification') }}</view>
          <view class="turnstile-wrapper">
            <view class="cf-turnstile" id="example-container" data-sitekey="0x4AAAAAABu1jaPmEM1vXznf"></view>
          </view>
        </view>

        
        <button class="register-btn" @click="bind()">
          <text class="btn-text">{{ t('Create Account') }}</text>
        </button>

        
        <view class="login-link">
          <text class="login-text">{{ t('Already have an account') }}? </text>
          <text class="login-btn" @click="goLogin()">{{ t('Sign In') }}</text>
        </view>
      </view>
    </view>

    
    <view v-if="baseData.showFullscreenLoading" class="loading-overlay">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{ t('login') }}</text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import '@/styles/auth-common.scss';

.register-container {
  @extend .auth-container;
}


.simple-header {
  @extend .simple-header;
}

.main-content {
  @extend .main-content;
}

.brand-section {
  @extend .brand-section;
}

.form-container {
  @extend .form-container;
}

.tab-switcher {
  @extend .tab-switcher;
}

.input-group {
  @extend .input-group;
}

.register-btn {
  @extend .circular-btn;
}

.login-link {
  @extend .auth-link;
}

.loading-overlay {
  @extend .loading-overlay;
}

</style>